# 加载模块
Import-Module WebAdministration

# 进入IIS模块
IIS:

# 获取脚本所在目录
$CurrentPath = Split-Path -Parent $MyInvocation.MyCommand.Definition;

# 读取配置文件
$Config = [xml](Get-Content $CurrentPath\Web.config);

# 配置开始
Main -config $Config;

# 回到脚本所在目录
cd $CurrentPath;


# 主入口
function Main(){
	Param(
		[parameter(Mandatory = $true)]
		$config = ''  # 配置文件对象
	 )

	# 遍历创建站点
	foreach($website in $config.configuration.websites.website){
		foreach($param in $website){
			$existsPort = Exists-Port -port $param.port;
			if($existsPort){
				Echo("端口 " + $param.port + " 被占用，站点 "+ $param.name +" 跳过！");
			}else{
				$existsWebsite = Exists-Website -siteName $param.name;
				if($existsWebsite){
					Echo("站点 " + $param.name + " 已存在，跳过！");
				}else{
					New-Website -websiteNme $param.name -port $param.port -websitePath $param.path -appPool $param.appPool;
				}
			}
		}	
	}

    # 遍历创建Windows服务
    foreach($windowsService in $config.configuration.windowsServices.windowsService){
		foreach($param in $windowsService){         
            $cmd_install = "& " + "'" + $param.path + "\" + $param.host + "'" + " Install";
            $cmd_start = "& "  + "'" + $param.path + "\" + $param.host + "'" + " Start";
            Invoke-Expression $cmd_install;
            Invoke-Expression $cmd_start;

            Echo("Windows服务 " + $param.host + " 创建完毕！");
		}
    }

    cd $CurrentPath;
}

# 端口是否被占用
function Exists-Port(){ 
	Param(
		[parameter(Mandatory = $true)]
		[string] $port = '' # 端口号
	)

	Get-ChildItem IIS:\sites | ForEach-Object {
		$site = $_;
		$bindingTokens = $site.bindings.collection.bindinginformation -split':';

		if($bindingTokens[1] -eq $port){
			return $site.name;
		}
	}
}

# 站点名称是否存在
function Exists-Website(){
	Param(
		[parameter(Mandatory = $true)]
		[string]$siteName = '' #站点名称
	)

	try
	{
		$site = Get-Item "IIS:\Sites\$siteName" -ErrorAction Stop;
		return $site;
	}catch [System.SystemException]{
		return $null;
	}
}

# 应用程序池是否存在
function Exists-AppPool(){
	Param(
		[parameter(Mandatory = $true)]
		[String]$AppPoolName = ""   # 主站点根目录
	)

	cd AppPools;
	$pools = ls;
	foreach($item in $pools){
		if($item.Name -eq $AppPoolName){
			cd..
			return $true;
		}
	}
	cd..
}

# 创建站点
function New-Website(){
	Param(
		[parameter(Mandatory = $true)]
		[string]$websiteNme = '',   #站点名称
		[parameter(Mandatory = $true)]
		[String]$port = '',         #端口号
		[parameter(Mandatory = $true)]
		[string]$websitePath = '',  #站点目录
		[parameter(Mandatory = $true)]
		[string]$appPool = ''       #应用程序池
	)

	# 站点目录是否存在，不存在则创建
	$existsWebsite = Test-Path $websitePath;
	if(!$existsWebsite){
		mkdir $websitePath;
	}

	# 应用程序池是否存在，不存在则创建
	$existsAppPool = Exists-AppPool -AppPoolName $appPool;
	if(!$existsAppPool){
		Echo("---------------------------------------------------");

		New-Item AppPools\$appPool
		Set-ItemProperty IIS:\AppPools\$appPool managedRuntimeVersion v4.0

		Echo("应用程序池 " + $appPool + " 初始化完毕！");
	}

	# 信息提示
	Echo("---------------------------------------------------");

	# 创建站点
	New-Item IIS:\Sites\$websiteNme -Bindings @{protocol='http';bindingInformation='*:'+$port+':'} -PhysicalPath $websitePath;

	# 修改站点应用程序池绑定
	Set-ItemProperty -path IIS:\Sites\$websiteNme -name applicationPool -value $appPool;

	# 信息提示
	Echo("站点 " + $websiteNme + " 部署完毕！");
}